package com.shqcjd.sinopecdemomobile.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.UploadBean;
import com.shqcjd.sinopecdemomobile.ui.activity.preview.VideosActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.AlbumUtils;
import com.shqcjd.sinopecdemomobile.util.MyGlideEngine;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.shqcjd.sinopecdemomobile.util.UIUtils;
import com.shqcjd.sinopecdemomobile.widget.FlowLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class UploadActivity extends BaseActivity {


    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.iv_upload_camera)
    ImageView ivUploadCamera;
    @BindView(R.id.fl_upload)
    FlowLayout layout;
    @BindView(R.id.iv_upload_delete)
    ImageView ivUploadDelete;
    @BindView(R.id.iv_upload_img)
    ImageView ivUploadImg;
    @BindView(R.id.iv_upload)
    ImageView ivUpload;
    @BindView(R.id.tv_upload)
    TextView tvUpload;
    @BindView(R.id.et_upload_name)
    EditText etUploadName;
    @BindView(R.id.et_upload_length)
    EditText etUploadLength;
    @BindView(R.id.et_upload_remark)
    EditText etUploadRemark;
    @BindView(R.id.ll)
    LinearLayout ll;

    private LinearLayout.MarginLayoutParams params;
    private Context context;
    private final int IMAGE_FILE_RESULT_CODE = 777;

    private String fileUrl = "";

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_upload;
    }

    @Override
    public void init() {
        super.init();
        context = this;
    }

    @Override
    public void initView() {
        super.initView();
        tvIncludeTitle.setText("视频上传");
        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ivUploadCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestLocationAndCallPermission();
            }
        });

        ivUploadDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fileUrl = "";
                visiblePic();
            }
        });

        ivUploadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!fileUrl.equals("")){
                    Intent it = new Intent(context, VideosActivity.class);
                    it.putExtra("url", fileUrl);
                    startActivity(it);
                }
            }
        });

        tvUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = etUploadName.getText().toString().trim();
                String length = etUploadLength.getText().toString().trim();
                String remark = etUploadRemark.getText().toString().trim();
                if(!fileUrl.equals("")){
                    if(!name.equals("")){
                        if(tagView.size()>0){
                            List<UploadBean.TagsBean> list = new ArrayList<>();
                            for(int i=0; i<tagView.size(); i++){
                                UploadBean.TagsBean mBean = new UploadBean.TagsBean();
                                mBean.tagName = tagView.get(i).getText().toString().trim();
                                list.add(mBean);
                            }
                            commitHttp(name, length, remark, list);
                        }else{
                            ToastUtils.showShort(context, "至少需要填写一个标签");
                        }
                    }else{
                        ToastUtils.showShort(context, "项目名称不能为空");
                    }
                }else{
                    ToastUtils.showShort(context, "上传的文件不能为空");
                }
            }
        });



        initFlowLayout();
    }

    public void RequestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Matisse.from(UploadActivity.this)
                                    .choose(MimeType.ofVideo()) // 选择 mime 的类型
                                    .countable(false)
                                    .maxSelectable(1) // 图片选择的最多数量
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f) // 缩略图的比例
                                    .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                                    .theme(R.style.Matisse_Zhihu)
//                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(true, getPackageName()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .forResult(IMAGE_FILE_RESULT_CODE); // 设置作为标记的请求码
                        } else {

                        }
                    }
                });
    }

    private void commitHttp(String name, String length, String remark, List<UploadBean.TagsBean> list){
        UploadBean uploadBean = new UploadBean();
        uploadBean.projectName = name;
        uploadBean.remark = remark;
        uploadBean.timeLength = length;
        uploadBean.url = fileUrl;
        uploadBean.tags = list;
        String json = new Gson().toJson(uploadBean);
        ApiService.commitUpload(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("上传文件中");
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> retData) {
                        if (retData.retCode == 10000) {
                            saveHttp(retData.data);
                        } else {
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(context, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void saveHttp(int knowledgeBaseId){
        ApiService.commitUploadSave(knowledgeBaseId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData.retCode == 10000) {
                            ToastUtils.showShort(context, "提交成功");
                            finish();
                        } else {
                            ToastUtils.showShort(context, "提交失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(context, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void uploadFile(File files ){
        ApiService.uploadMultiFile(files)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("上传文件中");
                    }

                    @Override
                    public void _onNext(ResponseData<String> retData) {
                        if (retData.retCode == 10000) {
                            fileUrl = retData.data;
                            visiblePic();
                        } else {
                            ToastUtils.showShort(context, "上传失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(context, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void visiblePic(){
        if(!fileUrl.equals("")){
            if(UIUtils.getFormatName(fileUrl).equals(".jpg")||UIUtils.getFormatName(fileUrl).equals(".png")){
                Glide.with(context).load(fileUrl).into(ivUploadImg);
            }else{
                RequestOptions options = new RequestOptions()
                        .placeholder(R.mipmap.ic_default_small)	//加载成功之前占位图
                        .error(R.mipmap.ic_default_small);//指定图片的缩放类型为centerCrop （等比例缩放图片，直到图片的宽高都
                Glide.with( context )
                        .load(fileUrl)
                        .apply(options)
                        .thumbnail( 0.1f )
                        .into(ivUploadImg);
            }
            ivUploadImg.setVisibility(View.VISIBLE);
            ivUploadCamera.setVisibility(View.GONE);
            ivUploadDelete.setVisibility(View.VISIBLE);
            ivUpload.setVisibility(View.GONE);
        }else{
            ivUploadImg.setVisibility(View.GONE);
            ivUploadCamera.setVisibility(View.VISIBLE);
            ivUploadDelete.setVisibility(View.GONE);
            ivUpload.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_FILE_RESULT_CODE && resultCode == RESULT_OK) {
            //图片上传
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    try {
                        String albumStringPath = AlbumUtils.getRealFilePath(this, uri);
                        uploadFile(new File(albumStringPath));
                        MediaPlayer mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(albumStringPath);
                        mediaPlayer.prepare();
                        etUploadLength.setText(secToTime(mediaPlayer.getDuration()/1000));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99)
                    return "99:59:59";
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Integer.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }

    final List<TextView> tagView=new ArrayList<>();
    private void initFlowLayout(){
        params = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.leftMargin = UIUtils.dp2px(5);
        params.bottomMargin = UIUtils.dp2px(3);
        //存放标签和标签选择状态
        final List<Boolean> tagViewState=new ArrayList<>();

        //创建编辑中的标签
        final EditText editText=new EditText(this);
        editText.setHint("添加标签");
        //设置固定宽度
        editText.setMinEms(4);
        editText.setTextSize(12);
        //设置shape
        editText.setBackgroundResource(R.drawable.tag_edit);
        editText.setHintTextColor(Color.parseColor("#b4b4b4"));
        editText.setTextColor(Color.parseColor("#000000"));
        editText.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        editText.setSingleLine(true);
        editText.setLayoutParams(params);


        //添加到layout中
        layout.addView(editText);

        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //回车键
                if(actionId == EditorInfo.IME_ACTION_NEXT){
                    String editTextContent = editText.getText().toString();
                    //判断输入是否为空
                    if (editTextContent.equals(""))
                        return true;
                    //判断标签是否重复添加
                    for(TextView tag:tagView){
                        String tempStr=tag.getText().toString();
                        if(tempStr.equals(editTextContent)) {
                            Log.e("tag","重复添加");
                            ToastUtils.showShort(context, "请勿重复添加");
                            editText.setText("");
                            editText.requestFocus();
                            return true;
                        }
                    }
                    //添加标签
                    final TextView temp = getTag(editText.getText().toString());
                    tagView.add(temp);
                    tagViewState.add(false);
                    //添加点击事件，点击变成选中状态，选中状态下被点击则删除
                    temp.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            int curIndex = tagView.indexOf(temp);
                            if (!tagViewState.get(curIndex)) {
                                //显示 ×号删除
                                temp.setText(temp.getText() + " ×");
                                temp.setBackgroundResource(R.drawable.tag_selected);
                                temp.setTextColor(Color.RED);
                                //修改选中状态
                                tagViewState.set(curIndex, true);
                            } else {
                                layout.removeView(temp);
                                tagView.remove(curIndex);
                                tagViewState.remove(curIndex);
                            }
                            return false;
                        }
                    });
                    layout.addView(temp);
                    //让编辑框在最后一个位置上
                    editText.bringToFront();
                    //清空编辑框
                    editText.setText("");
                    editText.requestFocus();
                    return true;
                }
                return true;
            }
        });

        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String editTextContent = editText.getText().toString();
                //判断输入是否为空
                if (editTextContent.equals(""))
                    return ;
                //判断标签是否重复添加
                for(TextView tag:tagView){
                    String tempStr=tag.getText().toString();
                    if(tempStr.equals(editTextContent)) {
                        Log.e("tag","重复添加");
                        ToastUtils.showShort(context, "请勿重复添加");
                        editText.setText("");
                        editText.requestFocus();
                        return ;
                    }
                }
                //添加标签
                final TextView temp = getTag(editText.getText().toString());
                tagView.add(temp);
                tagViewState.add(false);
                //添加点击事件，点击变成选中状态，选中状态下被点击则删除
                temp.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        int curIndex = tagView.indexOf(temp);
                        if (!tagViewState.get(curIndex)) {
                            //显示 ×号删除
                            temp.setText(temp.getText() + " ×");
                            temp.setBackgroundResource(R.drawable.tag_selected);
                            temp.setTextColor(Color.RED);
                            //修改选中状态
                            tagViewState.set(curIndex, true);
                        } else {
                            layout.removeView(temp);
                            tagView.remove(curIndex);
                            tagViewState.remove(curIndex);
                        }
                        return false;
                    }
                });
                layout.addView(temp);
                //让编辑框在最后一个位置上
                editText.bringToFront();
                //清空编辑框
                editText.setText("");
                editText.requestFocus();
            }
        });

        //对软键盘的Enter和Del键监听
        editText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (KeyEvent.ACTION_DOWN == event.getAction()) {
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_ENTER:
                            return true;
                        case KeyEvent.KEYCODE_DEL:
                            int lastIndex = tagView.size() - 1;
                            //没有添加标签则不继续执行
                            if (lastIndex < 0)
                                return false;
                            //获取前一个标签
                            TextView prevTag = tagView.get(lastIndex);
                            //第一次按下Del键则变成选中状态，选中状态下按Del键则删除
                            if (tagViewState.get(lastIndex)) {
                                tagView.remove(prevTag);
                                tagViewState.remove(lastIndex);
                                layout.removeView(prevTag);
                            } else {
                                String te = editText.getText().toString();
                                if (te.equals("")) {
                                    prevTag.setText(prevTag.getText() + " ×");
                                    prevTag.setBackgroundResource(R.drawable.tag_selected);
                                    prevTag.setTextColor(Color.RED);
                                    tagViewState.set(lastIndex, true);
                                }
                            }
                            break;
                    }

                }
                return false;
            }

        });

        //监听编辑标签的输入事件
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //输入文字时取消已经选中的标签
                for (int i = 0; i < tagViewState.size(); i++) {
                    if (tagViewState.get(i)) {
                        TextView tmp = tagView.get(i);
                        tmp.setText(tmp.getText().toString().replace(" ×", ""));
                        tagViewState.set(i, false);
                        tmp.setBackgroundResource(R.drawable.tag_normal);
                        tmp.setTextColor(Color.parseColor("#66CDAA"));
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    /**
     * 创建一个正常状态的标签
     * @param tag
     * @return
     */
    private TextView getTag(String tag){
        TextView textView=new TextView(getApplicationContext());
        textView.setTextSize(12);
        textView.setBackgroundResource(R.drawable.tag_normal);
        textView.setTextColor(Color.parseColor("#66CDAA"));
        textView.setText(tag);
        textView.setLayoutParams(params);
        return  textView;
    }
}
